package com.dianban.controller.nengliang;

import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.controller.BaseController;
import com.dianban.entity.FacePayStoreOrder;
import com.dianban.entity.FacePayStoreOrderShareLog;
import com.dianban.entity.User;
import com.dianban.service.FacePayStoreOrderService;
import com.dianban.service.FacePayStoreOrderShareLogService;
import com.dianban.service.UserService;
import com.dianban.utils.DateUtils;
import com.dianban.utils.RecommendCodeUtil;
import com.dianban.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "ApiFacePayStoreOrderShareController", description = "分享控制器")
@RestController
@RequestMapping(value = "${interfacePath}/nengliang/facePayStoreOrderShare/")
public class ApiFacePayStoreOrderShareController extends BaseController {

    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;
    @Autowired
    private FacePayStoreOrderShareLogService facePayStoreOrderShareLogService;
    @Autowired
    private UserService userService;

    @ApiOperation(notes = "list", httpMethod = "GET", value = "我的分享列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
    })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResultVo list(HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        List<FacePayStoreOrderShareLog> facePayStoreOrderShareLogList = facePayStoreOrderShareLogService.findList("", user.getId(), null);
        return ResultVo.success(facePayStoreOrderShareLogList, "获取成功");
    }

    @ApiOperation(notes = "share", httpMethod = "POST", value = "分享")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "orderId", value = "订单id", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "share", method = RequestMethod.POST)
    public ResultVo share(String orderId, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            String userToken = request.getHeader(UserUtils.USER_TOKEN);
            String key = RedisConstant.USER_TOKEN_KEY + userToken;
            User user = (User) RedisUtil.get(key);
            if (user == null) {
                return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
            }
            // 判断订单号是否是自己的,并且是有次数的
            FacePayStoreOrder order = facePayStoreOrderService.findById(Long.valueOf(orderId));
            if (order == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该订单");
            }
            if (!order.getUserId().equals(user.getId())) {
                return ResultVo.error(ResultCode.ERROR, "没有该订单的操作权限");
            }
            Integer canVerifyCount = order.getCanVerifyCount();
            Integer hasVerifyCount = order.getHasVerifyCount();
            if (canVerifyCount <= hasVerifyCount) {
                return ResultVo.error(ResultCode.ERROR, "该订单已无可用次数");
            }
            // 生成唯一
            String activationCode = RecommendCodeUtil.generateRecommendCode();
            FacePayStoreOrderShareLog shareLog = null;
            while (true) {
                shareLog = facePayStoreOrderShareLogService.findByCode(activationCode);
                if (shareLog == null) {
                    break;
                } else {
                    activationCode = RecommendCodeUtil.generateRecommendCode();
                }
            }
            FacePayStoreOrderShareLog facePayStoreOrderShareLog = new FacePayStoreOrderShareLog();
            facePayStoreOrderShareLog.setUserId(user.getId());
            facePayStoreOrderShareLog.setOrderId(Long.valueOf(orderId));
            facePayStoreOrderShareLog.setStatus("0");
            facePayStoreOrderShareLog.setCode(activationCode);
            facePayStoreOrderShareLogService.insert(facePayStoreOrderShareLog);
            // 生成code并返回
            // 扣除该订单的相应次数
            order.setCanVerifyCount(order.getCanVerifyCount() - 1);
            order.setSharingCount(order.getSharingCount() + 1);
            facePayStoreOrderService.update(order);
            // 认领码
            resultMap.put("activationCode", activationCode);
            // 推荐码
            resultMap.put("invitecode", user.getInvitecode());
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "分享失败");
        }
        return ResultVo.success(resultMap, "分享成功");
    }

    @ApiOperation(notes = "verify", httpMethod = "GET", value = "分享领取")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "code", value = "分享码", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "verify", method = RequestMethod.GET)
    public ResultVo verify(String code, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            String userToken = request.getHeader(UserUtils.USER_TOKEN);
            String key = RedisConstant.USER_TOKEN_KEY + userToken;
            User user = (User) RedisUtil.get(key);
            if (user == null) {
                return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
            }
            Long userId = user.getId();
            FacePayStoreOrderShareLog shareLog = facePayStoreOrderShareLogService.findByCode(code);
            if (shareLog == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该分享订单");
            }
            if (!"0".equals(shareLog.getStatus())) {
                return ResultVo.error(ResultCode.ERROR, "来晚了,该分享码已被领取");
            }
            Date createTime = new Date(shareLog.getCreatetime() * 1000);
            Date effectTimeEnd = DateUtils.addDays(createTime, 1);
            // 判断有效期
            if (DateUtils.format(effectTimeEnd, DateUtils.Y_M_D_H_M_S).compareTo(DateUtils.formatNow(DateUtils.Y_M_D_H_M_S)) < 0) {
                if (!"3".equals(shareLog.getStatus())) {
                    facePayStoreOrderShareLogService.update(shareLog.getId(), "3", null, null);
                    // 返回次数
                    FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findById(shareLog.getOrderId());
                    if (facePayStoreOrder != null) {
                        facePayStoreOrder.setSharingCount(facePayStoreOrder.getSharingCount() - 1);
                        facePayStoreOrder.setCanVerifyCount(facePayStoreOrder.getCanVerifyCount() + 1);
                        facePayStoreOrderService.update(facePayStoreOrder);
                    }
                }
                return ResultVo.error(ResultCode.ERROR, "来晚了,该分享码已过期失效");
            }
            //shareLog.setGetUserId(userId);
            //shareLog.setStatus("1");
            facePayStoreOrderShareLogService.update(shareLog.getId(), "1", shareLog.getUserId(), userId);
            FacePayStoreOrder order = facePayStoreOrderService.findById(Long.valueOf(shareLog.getOrderId()));
            if (order != null) {
                order.setSharingCount(order.getSharingCount() - 1);
                order.setHasShareCount(order.getHasShareCount() + 1);
                facePayStoreOrderService.update(order);
            }
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "操作失败");
        }
        return ResultVo.success(resultMap, "领取成功");
    }

    // 领取的时候判断有效期就可以了
    @ApiOperation(notes = "getShareInfo", httpMethod = "GET", value = "分享能量舱订单使用状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "分享码", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "getShareInfo", method = RequestMethod.GET)
    public ResultVo getShareInfo(String code, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            FacePayStoreOrderShareLog shareLog = facePayStoreOrderShareLogService.findByCode(code);
            if (shareLog == null) {
                return ResultVo.error(ResultCode.ERROR, "不存在该分享订单");
            }
            Date createTime = new Date(shareLog.getCreatetime() * 1000);
            Date effectTimeEnd = DateUtils.addDays(createTime, 1);
            String status = shareLog.getStatus();
            User shareUser = null;
            // 判断下是否已过有效期
            if (DateUtils.format(effectTimeEnd, DateUtils.Y_M_D_H_M_S).compareTo(DateUtils.formatNow(DateUtils.Y_M_D_H_M_S)) < 0) {
                status = "3";
                if (!"3".equals(shareLog.getStatus())) {
                    facePayStoreOrderShareLogService.update(shareLog.getId(), status, null, null);
                    // 返回次数
                    FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findById(shareLog.getOrderId());
                    if (facePayStoreOrder != null) {
                        facePayStoreOrder.setSharingCount(facePayStoreOrder.getSharingCount() - 1);
                        facePayStoreOrder.setCanVerifyCount(facePayStoreOrder.getCanVerifyCount() + 1);
                        facePayStoreOrderService.update(facePayStoreOrder);
                        User user = userService.findById(facePayStoreOrder.getUserId());
                        if (user != null) {
                            shareUser = new User();
                            shareUser.setAvatar(user.getAvatar());
                            shareUser.setMobile(user.getMobile());
                            shareUser.setNickname(user.getNickname());
                            shareUser.setId(user.getId());
                            shareUser.setInvitecode(user.getInvitecode());
                        }
                    }
                }
            }
            resultMap.put("code", code);
            resultMap.put("status", status);
            resultMap.put("shareUser", shareUser);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "操作失败");
        }
        return ResultVo.success(resultMap, "查询成功");
    }
}
